import cv2
import numpy as np

# 全局变量
drawing = False
center = (-1, -1)
radius = 0
img = None
img_original = None
img_display = None
scale_factor = 1.5  # 初始标准差倍数

def draw_circle(event, x, y, flags, param):
    global center, radius, drawing, img_display
    
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        center = (x, y)
        radius = 0
        img_display = img_original.copy()
    
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            radius = int(np.sqrt((x - center[0])**2 + (y - center[1])**2))
            img_display = img_original.copy()
            cv2.circle(img_display, center, radius, (0, 255, 0), 2)
            cv2.imshow('Image', img_display)
    
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        radius = int(np.sqrt((x - center[0])**2 + (y - center[1])**2))
        if radius > 0:
            img_display = img_original.copy()
            cv2.circle(img_display, center, radius, (0, 255, 0), 2)
            cv2.imshow('Image', img_display)
            analyze_color()

def create_circular_mask(h, w, center, radius):
    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y - center[1])**2)
    mask = dist_from_center <= radius
    return mask

def analyze_color():
    global center, radius, scale_factor
    
    if center[0] == -1 or radius == 0:
        return
    
    # 创建圆形掩码
    h, w = img_original.shape[:2]
    mask = create_circular_mask(h, w, center, radius)
    
    # 提取ROI区域
    roi = np.zeros_like(img_original)
    roi[mask] = img_original[mask]
    
    # 转换为HSV颜色空间
    hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    
    # 只处理掩码区域内的像素
    h_values = hsv_roi[:,:,0][mask]
    s_values = hsv_roi[:,:,1][mask]
    v_values = hsv_roi[:,:,2][mask]
    
    # 计算H、S、V通道的均值和标准差
    h_mean, h_std = np.mean(h_values), np.std(h_values)
    s_mean, s_std = np.mean(s_values), np.std(s_values)
    v_mean, v_std = np.mean(v_values), np.std(v_values)
    
    # 计算阈值范围（使用均值和标准差）
    h_low = max(0, int(h_mean - scale_factor * h_std))
    h_high = min(179, int(h_mean + scale_factor * h_std))
    
    s_low = max(0, int(s_mean - scale_factor * s_std))
    s_high = min(255, int(s_mean + scale_factor * s_std))
    
    v_low = max(0, int(v_mean - scale_factor * v_std))
    v_high = min(255, int(v_mean + scale_factor * v_std))
    
    # 显示结果
    print(f"\nHSV颜色阈值范围 (倍数: {scale_factor:.1f}):")
    print(f"H: [{h_low}, {h_high}]")
    print(f"S: [{s_low}, {s_high}]")
    print(f"V: [{v_low}, {v_high}]")
    
    # 创建颜色掩码并显示结果
    lower_bound = np.array([h_low, s_low, v_low])
    upper_bound = np.array([h_high, s_high, v_high])
    
    # 在整个图像上应用颜色阈值
    hsv_img = cv2.cvtColor(img_original, cv2.COLOR_BGR2HSV)
    color_mask = cv2.inRange(hsv_img, lower_bound, upper_bound)
    result = cv2.bitwise_and(img_original, img_original, mask=color_mask)
    
    # 显示ROI区域
    roi_display = np.zeros_like(img_original)
    roi_display[mask] = img_original[mask]
    return roi_display, lower_bound.tolist(), upper_bound.tolist()
    # cv2.imshow('Selected ROI', roi_display)
    
    # # 显示颜色掩码和结果
    # cv2.imshow('Color Mask', color_mask)
    # cv2.imshow('Filtered Result', result)
    
    # # 更新阈值显示
    # cv2.displayOverlay('Image', f'H: [{h_low}-{h_high}] S: [{s_low}-{s_high}] V: [{v_low}-{v_high}]', 1000)

def detect_color_hsv(img, x, y, r = 10, scale = 1.5):
    global img_original, img_display, center, radius, scale_factor
    scale_factor = scale
    img_original = img
    radius = r
    img_display = img_original.copy()
    center = (x, y)
    return analyze_color()


if __name__ == "__main__":
    img = cv2.imread("leaf.png")
    roi_display, lower_bound, upper_bound = detect_color_hsv(img, 240, 180)
    print(lower_bound, upper_bound)
    cv2.imshow('roi', roi_display)
    cv2.waitKey(0)